home *** CD-ROM | disk | FTP | other *** search
- Path: atglab.bls.com!Alun.Champion
- From: Alun.Champion@bridge.bst.bls.com (Alun Champion)
- Newsgroups: comp.lang.c++
- Subject: Re: Overload >> vs. Write Met
- Date: 26 Jan 1996 16:57:01 GMT
- Organization: Computer People Inc.
- Message-ID: <ALUN.CHAMPION.96Jan26115701@g7240065.bridge.bst.bls.com>
- References: <60125190005$71C7@lasernet.com>
- NNTP-Posting-Host: bstfirewall.bst.bls.com
- In-reply-to: GEORGE BOUTWELL's message of Thu, 25 Jan 96 16:20:00 LOC
-
- In article <60125190005$71C7@lasernet.com> GEORGE BOUTWELL <george_boutwell@lasernet.com> writes:
-
- : Ok...
-
- : Which is 'better' OOP 'Style', and/or 'Correctness' for
- : Writing/Reading an Object's Data to/from Disk/Screen/Etc:
-
- : Overloading the << and >>
- : -or-
- : writing a read method and a write method?
-
- IMHO both.
-
- The problem with the operators << and >> is that they are usually (friend)
- global functions and as such cannot be virtual.
-
- The advantage of operator >> and << is that you read and write things
- from a stream in a consistent way.
-
- Read and write have the advantage of being able to be virtual.
-
- So the best solution is to combine them - implement operator << and >>
- in terms of read and write
-
- Example - only deals with write, read is left for an exercise of the reader ;')
-
- #include <iostream.h>
-
- class Base
- {
- public:
- virtual ostream& write(ostream& out) const
- { return out << "Base" << endl; }
- };
-
- ostream& operator << (ostream& out, const Base& base)
- {
- return base.write(out);
- }
-
- class Derived : public Base
- {
- public:
- virtual ostream& write(ostream& out) const
- { return out << "Derived" << endl; }
- };
-
- int
- main(void)
- {
- Base b;
- Derived d;
- Base& ref = d;
-
- cout << b; // writes "Base"
- cout << d; // writes "Derived"
- cout << ref; // writes "Derived"
-
- return 0;
- }
-
- Regards
-
- -A.
- --
- | A.Champion |
-